package com.molyfun.parents.activity.organization;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.maning.library.zxing.CaptureActivity;
import com.maning.library.zxing.ZXingConstants;
import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.activity.signup.SignUpStartActivity;
import com.molyfun.parents.fragment.dialog.OrganizationSignUpListFragment;
import com.molyfun.parents.rest.bean.SignUpNoticeResponse;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.SinglineClearEditText;

import java.util.ArrayList;
import java.util.Arrays;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OrganizationEnterActivity extends BaseActivity implements View.OnClickListener {

    private String TAG = "OrganizationEnterActivity";
    private int ORGANIZATIONeNTER_REQUESTCODE = 0x001;
    @InjectView(R.id.base_title_left)
    ImageView mBack;
    @InjectView(R.id.base_title)
    TextView mTitle;

    @InjectView(R.id.organization_mark)
    SinglineClearEditText mOrganizationMark;
    @InjectView(R.id.scan_button)
    TextView mScanButton;
    @InjectView(R.id.submit)
    TextView mConfirmOrganizationInfo;
    private String mCodeValue = "";
    private String departid = "";

    public static void startActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, OrganizationEnterActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_organization_enter);
        ButterKnife.inject(this);
        initView();

    }

    private void initView() {
        getSupportActionBar().setTitle("");
        mTitle.setText("申请加入机构");
        mConfirmOrganizationInfo.setText("提交");
        mOrganizationMark.setHint("请输入您的手机号码");
        mBack.setOnClickListener(this);
        mScanButton.setOnClickListener(this);
        mConfirmOrganizationInfo.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_title_left:
                finish();
                break;
            case R.id.submit:
                mCodeValue = mOrganizationMark.getString();
                if (!TextUtils.isEmpty(mCodeValue)) {
                    loadData(mCodeValue, departid);
                } else {
                    toast("机构代码为空");
                }

                break;
            case R.id.scan_button:
                //TODO 扫描二维码
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent, ORGANIZATIONeNTER_REQUESTCODE);
                break;
        }

    }

    /**
     * //测试服 http://192.168.3.30:8081/helloapply-client/#/apply/login?code=A0000004&departid=8a2d9263540d4e2f01540d57421b0001
     * <p>
     * //预发布
     * //  http://h5.helloapplytest.molyfun.com/#/apply/login?code=A0011111&departid=8a2d9263540d4e2f01540d57421b0001
     * <p>
     * //正式服
     * //  http://h5.helloapply.molyfun.com/#/apply/login?code=A0011111&departid=8a2d9263540d4e2f01540d57421b0001
     */
    // 回调获取扫描得到的条码值
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        if (requestCode == ORGANIZATIONeNTER_REQUESTCODE && resultCode == ZXingConstants.ScanRequltCode) {
            /**
             * 拿到解析完成的字符串
             */
            String result = data.getStringExtra(ZXingConstants.ScanResult);
            System.out.println("result--->" + result);
            String[] codeUrl = result.split("\\?");
            //TODO 请求网络是数据开始报名
            String contents = result;
            String[] strs = contents.split("\\=");
            String[] arrDepart = strs[1].split("departid=");

            String[] split = arrDepart[0].split("&");

            if (split[0].equals(null)) {
                mCodeValue = "";
            } else {
                mCodeValue = split[0];
            }
            if (strs[2].equals(null)) {
                departid = "";
            } else {
                departid = strs[2];
            }
            if (codeUrl[0].equals("http://192.168.3.30:8081/helloparents-client/#/user/login") && (PreferencesStorageUtil.getServerMode(MFPApplication.getInstance())) == PreferencesStorageUtil.ServerMode.TEST) {
                //测试
                loadData(mCodeValue, departid);

            } else if (codeUrl[0].equals("http://h5.helloparentstest.molyfun.com/#/user/login") && (PreferencesStorageUtil.getServerMode(MFPApplication.getInstance())) == PreferencesStorageUtil.ServerMode.PREPARE) {
                //预发

                loadData(mCodeValue, departid);
            } else if (codeUrl[0].equals("http://h5.helloparents.molyfun.com/#/user/login") && (PreferencesStorageUtil.getServerMode(MFPApplication.getInstance())) == PreferencesStorageUtil.ServerMode.OFFICAL) {
                //正式
                loadData(mCodeValue, departid);
            } else {
                toast("该二维码不可用");
                return;
            }
        } else {
            Toast.makeText(this, "扫码取消！", Toast.LENGTH_LONG).show();

        }
    }

    private void loadData(final String codeValue, final String departid) {
        showProgressDialog();
        Call<SignUpNoticeResponse> call = MFPApplication.getInstance().getRestClient().signUpNotice(codeValue, "enroll");
        call.enqueue(new Callback<SignUpNoticeResponse>() {

            @Override
            public void onResponse(Call<SignUpNoticeResponse> call, final Response<SignUpNoticeResponse> response) {
                dismissProgressDialog();
                if(response.body() != null){
                    if(response.body().getCode() == 200){
                        if(response.body().getData().isJsonArray()){
                            new OrganizationSignUpListFragment.OrganizationSignUpListDialogBuilder(new ArrayList<>(Arrays.asList(GsonUtil.fromJson(response.body().getData(), SignUpNoticeResponse.SignUpInfo[].class))))
                                    .setOrganizationSignUpCallback(new OrganizationSignUpListFragment.OrganizationSignUpCallback() {
                                        @Override
                                        public void onSignUpContinue() {
                                            getOrganInfo(codeValue);
                                        }

                                        @Override
                                        public void onCancel() {
                                            mCodeValue = "";
                                        }
                                    })
                                    .build(getSupportFragmentManager().beginTransaction());
                        }else if(response.body().getData().isJsonObject()){
                            SignUpStartActivity.startActivity(OrganizationEnterActivity.this, GsonUtil.fromJson(response.body().getData(), SignUpNoticeResponse.SignUpNotice.class));
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<SignUpNoticeResponse> call, Throwable t) {
                dismissProgressDialog();
                toast("报名失败");
            }
        });
    }


    private void getOrganInfo(final String codeValue) {
        showProgressDialog();
        Call<SignUpNoticeResponse> call = MFPApplication.getInstance().getRestClient().signUpNotice(codeValue, "continue");
        call.enqueue(new Callback<SignUpNoticeResponse>() {

            @Override
            public void onResponse(Call<SignUpNoticeResponse> call, final Response<SignUpNoticeResponse> response) {
                dismissProgressDialog();
                if(response.body() != null) {
                    if (response.body().getCode() == 200) {
                        SignUpStartActivity.startActivity(OrganizationEnterActivity.this, GsonUtil.fromJson(response.body().getData(), SignUpNoticeResponse.SignUpNotice.class));
                    }
                }
            }

            @Override
            public void onFailure(Call<SignUpNoticeResponse> call, Throwable t) {
                dismissProgressDialog();
                toast("报名失败");
            }
        });
    }

    private Handler mHandler = new Handler();

}
